<?php
class allocate extends Activity {
    function orderStateTask($code){
        if($code!='7fbab2b2f3c7a8d6251d3f638c89a44f') return null;
        $orderMode=OrderMode::init();
        $goodsMode=GoodsMode::init();
        list($order1,$total1)=$orderMode->getList(null,null,'received',null,null,null,0,null,100,0);
        list($order2,$total2)=$orderMode->getList(null,null,'shipped_direct',null,null,null,0,null,100,0);
        $orders=array_merge($order1, $order2);
        foreach($orders as $order){
            if($order['state']=='received'&&strtotime($order['delivery_time'])+60*60*24*7<time() ||
                $order['state']=='shipped_direct'&&strtotime($order['shipping_time'])+60*60*24*15<time()){
                $id=(int)$order['id'];
                // 设置状态
                $orderMode->setState($id,'confirmed');
                // 修改销量
                $goods=$orderMode->getGoodsInOrder($id);
                if(empty($goods)) continue;
                foreach($goods as $v){
                    $goodsMode->modifySale($v['gopen_id'],$v['number']);
                }
            }
        }
        echo "结算系统";
    }
    function orderTask($code){
        if($code!='7fbab2b2f3c7a8d6251d3f638c89a44f') return null;
        $orderMode=OrderMode::init();
        $moneyMode=MoneyMode::init();
        $userMode=UserMode::init();
        $serviceMode=ServiceMode::init();
        $shopMode=ShopMode::init();

        list($order1,$total)=$orderMode->getList(null,null,'confirmed',null,null,null,0,null,100,0);
        list($order2,$total2)=$orderMode->getList(null,null,'evaluate',null,null,null,0,null,100,0);
        $orders=array_merge($order1, $order2);
        $total+=$total2;

        foreach($orders as $order){
            $commission=0;
            $buyerId=$order['buyer_id'];
            $serviceFee=0;
            $serverId=$order['service_id'];
            $shareArray=array();
            $shareTotal=0;
            $platFee=0;

            foreach($order['goods'] as $goods){
                $commission+=$goods['commission']*$goods['number'];
                $platFee+=$goods['platform_fee']*$goods['number'];
                if($order['type']=='normal'){
                    $serviceFee+=$goods['service_fee']*$goods['number'];
                }
                if(!empty($goods['share_id'])){
                    // 如果存在分享人，则增加
                    if(!isset($shareArray[$goods['share_id']])) $shareArray[$goods['share_id']]=0;
                    $shareArray[$goods['share_id']]+=$goods['bonus']*$goods['number'];
                    $shareTotal+=$goods['bonus']*$goods['number'];
                }
            }

            $orderTotal=$order['order_amount'];
            // 给服务站服务费
            if(!empty($serverId)&& $serviceFee!=0){
                $serverUserId=$serviceMode->getUserId($serverId);
                $serviceInfo=$userMode->getDetail($serverUserId);
                $moneyMode->add($serverUserId,"订单号{$order['id']}的服务费",$serviceFee,$serviceInfo['money']+$serviceFee,
                    date("Y-m-d")."收到服务费{$serviceFee}元",null,"serviceFee","money",1,$order['id']);
                $moneyMode->updateMoney($serverUserId,$serviceFee,true);
                $orderTotal-=$serviceFee;
            }else{
                $serviceFee=0;
            }

            // 给分享人
            foreach($shareArray as $shareId=>$bonus){
                $shareInfo=$userMode->getDetail($shareId);
                $moneyMode->add($shareId,"订单号{$order['id']}的分享提成",$bonus,$shareInfo['money']+$bonus,
                    date("Y-m-d")."收到分享提成{$bonus}元",null,"share","money",1,$order['id']);
                $moneyMode->updateMoney($shareId,$bonus,true);
            }
            $orderTotal-=$shareTotal;

            // 给代购人
            if(!empty($buyerId)){
                $buyerInfo=$userMode->getDetail($buyerId);
                $moneyMode->add($buyerId,"订单号{$order['id']}的代购提成",$commission,$buyerInfo['money']+$commission,
                    date("Y-m-d")."收到代购提成{$commission}元",null,"buy","money",1,$order['id']);
                $moneyMode->updateMoney($buyerId,$commission,true);
                $orderTotal-=$commission;
            }else{
                $commission=0;
            }

            // 系统平台服务费
          
            if($platFee!=0){
                $orderTotal-=$platFee;
                $platId=  UserMode::getplat_id();
                $platuserInfo=$userMode->getDetail($platId);
                $moneyMode->add('',"订单号{$order['id']}的平台费",$platFee,$platuserInfo['money']+$platFee,
                    date("Y-m-d")."收到平台费{$platFee}元",null,"platform_fee","money",1,$order['id']);
                $moneyMode->updateMoney($platId,$platFee,true);
            }else{
                $platFee=0;
            }

            // 给商家
            $shopUserId=$shopMode->getUserId($order['shop_id']);
            $shopInfo=$userMode->getDetail($shopUserId);
            $moneyMode->add($shopUserId,"订单号{$order['id']}的订单款项(已扣除服务费与提成)",$orderTotal,$shopInfo['money']+$orderTotal,
                date("Y-m-d")."收到订单款项{$orderTotal}元(已扣除服务费{$serviceFee}元,分享提成{$shareTotal}元,代购提成{$commission}元,系统服务费提成{$platFee}元)",null,"shopSell","money",1,$order['id']);
            $moneyMode->updateMoney($shopUserId,$orderTotal,true);

            $orderMode->setAllocate($order['id']);
        }
        echo "结算系统";
    }

    function refundTask($code){
        if($code!='7fbab2b2f3c7a8d6251d3f638c89a44f') return null;
        $orderMode=OrderMode::init();
        $moneyMode=MoneyMode::init();
        $userMode=UserMode::init();
        list($refunds,$total)=$orderMode->getSimpleRefundList('confirm',0);
        foreach($refunds as $refund){
            $userId=$refund['user_id'];
            $userInfo=$userMode->getDetail($userId);
            $moneyMode->add($userId,"退款号{$refund['id']}的订单退款",
                $refund['money'],$userInfo['money']+$refund['money'],
                date("Y-m-d")."收到退款",null,"shopSell","money",1,$refund['order_id']);
            $moneyMode->updateMoney($userId,$refund['money'],true);

            $orderMode->setRefundAllocate($refund['id']);
        }
        echo "结算系统";
    }
    function notify_urlTask(){
        require_once("alipay/alipay.config.php");
        require_once("alipay/lib/alipay_notify.class.php");
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];
            $moneyMode = MoneyMode::init();
            $moneyMode->addNotifyInfo($out_trade_no,$trade_no,$trade_status);

            if($_POST['trade_status'] == 'TRADE_FINISHED' ) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //该种交易状态只在两种情况下出现
                //1、开通了普通即时到账，买家付款成功后。
                //2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。

                //调试用，写文本函数记录程序运行情况是否正常
//                    logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");


            } else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。

                //调试用，写文本函数记录程序运行情况是否正常
//                    logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
                if(!$moneyMode->checkHistoryDealed($out_trade_no)){
                    $userId=$moneyMode->getUserIdById($out_trade_no);
                    $moneyMode->updateMoney($userId,$_POST['total_fee'],true);//money inc
                    $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
                    $order_ids=$moneyMode->getOrderIdsById($out_trade_no);
                    if(!empty($order_ids)){
                        $moneyMode->setSuccessSymbol($out_trade_no,$trade_no,$userInfo['money'],1);
                        $order_ids_arr=explode(',',$order_ids);
                        foreach ($order_ids_arr as $v) {
                            $order_id=$v;
                            $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
                            $orderInfo=OrderMode::init()->getDetailWithoutJoin($order_id);
                            $payR=$moneyMode->moneyPay($userId,$orderInfo['payment_amount'],$orderInfo['payment_amount']);
                            if($payR){  //余额支付成功
                                $this->handingUserInfo($userId,$userInfo['point'],$orderInfo['point'],
                                    $orderInfo['id'],$orderInfo['user_coupon_id'],$orderInfo['order_amount'],
                                    $orderInfo['payment_amount'],$orderInfo['type']);
                                $remark=OrderMode::init()->getRemarkOfOrder($order_id);
                                $moneyMode->add($userId,'支付订单'.$order_id, -$orderInfo['payment_amount'],$userInfo['money']-$orderInfo['payment_amount'],
                                    date("Y-m-d H:i:s",time()).$remark,null,null,'money',1,$order_id);//生成流水记录
                            }
                        }
                    }else{//仅充值
                        $moneyMode->setSuccessSymbol($out_trade_no,$trade_no,$userInfo['money'],1);
                    }
                }
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
//                logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }
    //处理各种支付后的用户增长值
    function handingUserInfo($userId,$userPoint,$point,$order_id,$user_coupon_id,
                             $order_amount,$payment_amount,$type){
        $state=$type=='normal'?'unshipped':'unused';
        OrderMode::init()->setState($order_id,$state);
        if(!empty($point)){
            //判断point<=paymen_amount*10%
            $point = $point<=$order_amount*10.0? $point : $order_amount*10.0;
            $point = $point > $userPoint? $userPoint:$point;
            PointMode::init()->usePoint($userId,$point,'订单'.$order_id.'使用积分',$payment_amount);
        }
        if(!empty($user_coupon_id)){
            CouponMode::init()->using($user_coupon_id,$order_id);
        }
        //支付成功，积分要涨，成长值要涨
        if((int)$payment_amount>0){
            PointMode::init()->earnPoint($userId,(int)$payment_amount,'购买获得积分',$payment_amount);
            $id=UserMode::init()->getIdByUserId($userId);
            UserMode::init()->modifyGrowth($id,$payment_amount,true);
        }
        return; //不知道应该返回什么 TODO
    }
}